package com.ruoyi.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.model.TXIMUserAccount;
import com.ruoyi.common.utils.ChineseCharacterGeneratorUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.user.service.PlanetUserService;
import com.ruoyi.user.service.TXIMUserService;
import com.ruoyi.user.verification.LoginVerification;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;


/**
 * 行星用户服务实现类
 *
 * @author mrj
 */
@RequiredArgsConstructor
@Service
public class PlanetUserServiceImpl implements PlanetUserService {

    private final ISysConfigService sysConfigService;
    private final SysUserMapper sysUserMapper;
    private final TXIMUserService tximUserService;

    @Override
    public String login(String username, String password, String code) {
        String msg = LoginVerification.login(username, password, code, UserConstants.REGULAR_USER);
        if ("登录成功".equals(msg)) {
            SysUser oldSysUser = sysUserMapper.selectUserByUserName(username, UserConstants.REGULAR_USER);
            if (ObjectUtil.isNull(oldSysUser)) {
                SysUser sysUser = new SysUser();
                sysUser.setUserName(username);
                sysUser.setPhonenumber(username);
                sysUser.setPassword(SecurityUtils.encryptPassword(sysConfigService.selectConfigByKey("sys.user.initPassword")));
                sysUser.setNickName(ChineseCharacterGeneratorUtils.generateChineseCharacters(6));
                sysUser.setUserType(UserConstants.REGULAR_USER);
                sysUser.setPhonenumber(username);
                TXIMUserAccount tximUserAccount = new TXIMUserAccount();
                tximUserAccount.setUserId(username);
                tximUserAccount.setNick(sysUser.getNickName());
                String url = "https://im.sdk.qcloud.com/download/tuikit-resource/avatar/avatar_12.png";
                tximUserAccount.setFaceUrl(url);
                if(tximUserService.accountImport(tximUserAccount)){
                    boolean regFlag = sysUserMapper.insertUser(sysUser)>0;
                    if (!regFlag) {
                        msg = "注册失败,请联系系统管理人员";
                    }
                }else{
                    msg = "注册失败,请联系系统管理人员";
                }

            }
        }
        return msg;
    }

}
